package cn.tedu.tmall.front.mall.dao.search.impl;

import cn.tedu.tmall.common.pojo.po.GoodsSearchPO;
import cn.tedu.tmall.common.pojo.vo.PageData;
import cn.tedu.tmall.front.mall.dao.search.GoodsElasticsearchRepository;
import cn.tedu.tmall.front.mall.dao.search.IGoodsSearchRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;


@Repository
public class GoodsSearchRepositoryImpl implements IGoodsSearchRepository {

    @Autowired
    private GoodsElasticsearchRepository goodsElasticsearchRepository;

    @Override
    public PageData<GoodsSearchPO> search(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(--pageNum,pageSize);
        SearchPage<GoodsSearchPO> searchPage = goodsElasticsearchRepository.customSearch(keyword, pageable);

        SearchHits<GoodsSearchPO> searchHits = searchPage.getSearchHits();

        PageData<GoodsSearchPO> pageData = new PageData<>();
        pageData.setPageNum(pageNum + 1);
        pageData.setPageSize(pageSize);
        pageData.setMaxPage(searchPage.getTotalPages());
        pageData.setTotal(searchHits.getTotalHits());

        ArrayList<GoodsSearchPO> goodsList = new ArrayList<>();
        for (SearchHit<GoodsSearchPO> searchHit : searchHits) {
            GoodsSearchPO goodsSearchPO = searchHit.getContent();
            List<String> highlightFieldList = searchHit.getHighlightField("title");
            if (highlightFieldList.size() > 0) {
                goodsSearchPO.setTitle(highlightFieldList.get(0));
            }
            goodsList.add(goodsSearchPO);
        }
        pageData.setList(goodsList);
        return pageData;
    }
}
